package com.lovezy.platform.filestore.controller;

import com.google.common.collect.ImmutableMap;
import com.lovezy.platform.core.base.Response;
import com.lovezy.platform.core.base.SiteContext;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.filestore.oss.OssBucket;
import com.lovezy.platform.filestore.oss.OssBucketChooser;
import com.lovezy.platform.filestore.service.FileService;
import com.lovezy.platform.filestore.vo.FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

import static com.lovezy.platform.core.base.Response.ok;

/**
 * File Store Controller
 * Created by jin on 2017/11/6.
 */
@RestController
@RequestMapping("/api/filestore")
public class FileStoreController {

    @Autowired
    private FileService fileService;

    @Autowired
    OssBucketChooser ossBucketChooser;

    @GetMapping("/download/{url:.+}")
    public ResponseEntity<byte[]> download(@PathVariable("url")String url,String name) {
        return fileService.downloadFile(url, name);
    }

    @GetMapping("/oss")
    public ResponseEntity<Response> ossUrl(@RequestParam("url") String url) {
        String s = fileService.downloadUrl(url);
        return ResponseEntity.ok(ok(ImmutableMap.of("url",s)));
    }

    @PostMapping("/upload")
    public ResponseEntity<Response> upload(@RequestParam MultipartFile file,
                                           @RequestParam(defaultValue = "oss",required = false) String bucket) {
        try{
            OssBucket ossBucket = ossBucketChooser.bucketOf(bucket);
            FileVo fileVo = fileService.uploadFile(file, ossBucket.getBucket(), SiteContext.getCurrentMid());
            return new ResponseEntity<>(ok(fileVo), HttpStatus.CREATED);
        }catch (IllegalArgumentException e){
            throw new ServiceException("bucket参数错误");
        }
    }

    @PostMapping("/uploadToken")
    public ResponseEntity<Response> uploadToken(@RequestParam(defaultValue = "oss",required = false) String bucket,@RequestParam String fileName) {
        OssBucket ossBucket = ossBucketChooser.bucketOf(bucket);
        Map<String, String> uploadToken = fileService.createUploadToken(ossBucket, fileName);
        return ResponseEntity.ok(ok(uploadToken));
    }

}
